package smashedapples.amazon.productapi
{
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import smashedapples.amazon.ProductApi;
	import smashedapples.core.NonVisualComponent;
	
	[Bindable]
	public class BaseRequest extends NonVisualComponent
	{
		
		
		public var AssociateTag:String;
		
		private var _AWSAccessKeyId:String;
		public function get AWSAccessKeyId():String
		{
			if( _AWSAccessKeyId != null )
				return _AWSAccessKeyId;
			
			if( this.api.AWSAccessKeyId != null )
				return this.api.AWSAccessKeyId;
			
			return null;			
		}
		public function set AWSAccessKeyId( value:String ):void
		{		
			_AWSAccessKeyId = value;	
		}
		
		
		public var ContentType:String;
		
		public var MerchantId:String;
		
		public var Operation:String;
		
		public var Service:String = ProductApiConsts.SERVICE_AWSECommerceService;
		
		public var Style:String;
		
		[Inspectable(enumeration="True,False")]
		public var Validate:String;
		
		public var Version:String = ProductApiConsts.VERSION_2009_05_08;
		
		[Inspectable(enumeration="Single,Double")]
		public var XMLEscaping:String;
		
		private var result:Function;
		private var fault:Function;
		
		public function BaseRequest():void{}
		
		
		private var originalParamNames:Array = [ "AssociateTag","AWSAccessKeyId","ContentType","Operation","Service","Style","Validate","XMLEscaping" ];
		protected var paramNames:Array = [];
		
		protected function addParamNames( params:Array, concat:Boolean = true ):void
		{
			if( concat == false || paramNames.length == 0)
				this.paramNames = originalParamNames;
			
			for each( var param:String in params )
			{
				paramNames.push( param );
			}
		}
		
		
		public function send():void
		{
			
			var params : Object = getParams();
			
			addToDebug( params );
			
			var service:HTTPService = new HTTPService();
				service.url = ProductApiConsts.API_URL;
				service.addEventListener( ResultEvent.RESULT, handleResultEvent );
				service.addEventListener( FaultEvent.FAULT, handleFaultEvent );
				
				service.send( params );
		}
		
		private function getParams():Object
		{
			var params:Object = {};
			
			for each( var property:String in this.paramNames )
			{
				if( this[property] != null )
					params[property] = this[property];
			}
			
			return params;
		}
		
		private function handleResultEvent( event:ResultEvent ):void
		{
			addToDebug( event.result );
		}
		
		private function handleFaultEvent( event:FaultEvent ):void
		{
			addToDebug( event.fault );
		}
		
		private var _api:ProductApi;
		
		public function get api():ProductApi
		{
			return _api;
		}
		
		public function set api( value:ProductApi ):void
		{
			_api = value;
		}
		
		private function addToDebug( output:*,showTrace:Boolean = false ):void
		{
			Debug.push( this, output, showTrace );
		}
		
		
	}
}